const express = require('express');
const app = express();
app.use(express.static('www'));


const http = require('http');
// 创建一个server服务器
const server = http.createServer(app);

const WebSocket = require('ws');
const WebSocketServer = new WebSocket.Server({ server })



var userList = [];
WebSocketServer.on('connection', function (ws, req) {
    // console.log('ws',ws);
    // console.log('req',req);
    console.log(req.url);

    var user = req.url.substring(1);

    ws.username = user;
    ws.send(JSON.stringify(obj));

    ws.username = req.url.substring(1);
    ws.username = decodeURI(ws.username)

    userList.forEach((item) => {
        var obj = {
            data: `${user}进来了`
        }
        item.send(JSON.stringify(obj));
    })
    userList.push(ws);


    var obj = {
        data: `${user}欢迎来到聊天室`
    }


    ws.send(JSON.stringify(obj));


    ws.on('message', function (req) {
        var res = JSON.parse(req)
        console.log(res);
    })


})



server.listen(3000, () => {
    console.log('localhost:3000');
})